package echo.nio;

//import lombok.extern.slf4j.Slf4j;
//import org.omg.SendingContext.RunTime;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author： zhangnan
 * @date： 2025/4/23 17:14
 * @description： 多线程nio服务端
 * @modifiedBy：
 * @version: 1.0
 */
@Slf4j
public class MultiThreadServer {
public static void main(String[] args) {
        try {
            Thread.currentThread().setName("boss");
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.configureBlocking(false); // nio模式
            Selector boss = Selector.open();
            SelectionKey bossKey = ssc.register(boss, 0, null);
            bossKey.interestOps(SelectionKey.OP_ACCEPT);
            ssc.bind(new InetSocketAddress(8080));
            // 创建work线程
//            Worker worker = new Worker("worker-0");
            // 创建固定数量的 worker 并初始化
            // 如何拿到 cpu 个数
            // Runtime.getRuntime().availableProcessors()如果工作在 docker 容器下，
            // 因为容器不是物理隔离的会拿到物理 cpu 个数，而不是容器申请时的个数，这样会导致拿到的CPU个数大于容器分配到的CPU个数
            // 这个问题直到 jdk 10 才修复，使用jvm 参数 UseContainerSupport 配置，默认开启
            Worker[] workers = new Worker[Runtime.getRuntime().availableProcessors()]; // 可以配置成cup的核心数
            for (int i = 0; i < workers.length; i++) {
                workers[i] = new Worker("worker-" + i);
            }
            AtomicInteger index = new AtomicInteger(); // 轮询算法用
            while (true) {
                // select方法没有事件发生,线程阻塞，有事件，线程才会恢复运行
                log.debug("boss开始阻塞等待处理事件。。。");
                boss.select();
                Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
                while (iter.hasNext()) {
                    SelectionKey key = iter.next();
                    iter.remove();
                    if (key.isAcceptable()) {
                        SocketChannel sc = ssc.accept();  // 需要交给工作线程处理的Channel
                        sc.configureBlocking(false); // 非阻塞的
                        log.debug("connected...{}", sc.getRemoteAddress());
                        // 2. 关联selector
                        log.debug("before register...{}",sc.getRemoteAddress());
                        // round robin
                        workers[index.getAndIncrement() % workers.length].register(sc); // boss 调用 初始化 selector，启动 woker-
                        log.debug("after register...{}",sc.getRemoteAddress());
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    static class Worker implements Runnable {
        private Thread thread;
        private Selector selector;
        private String name;
        //        private ConcurrentLinkedDeque<Runnable> queue = new ConcurrentLinkedDeque<>(); // boss和worker线程间传递数据
        private volatile boolean start = false; // 还未初始化

        public Worker(String name) {
            this.name = name;
        }

        // 初始化线程，和 selector
        public void register(SocketChannel sc) throws IOException {
            if (!start) {
                selector = Selector.open(); // worker 的 select
                thread = new Thread(this, name);
                thread.start();
                start = true;
            }
            selector.wakeup(); // 唤醒selector方法
//            queue.add(() -> {
//                try {
//                    sc.register(selector,SelectionKey.OP_READ,null);
//                }catch (Exception e) {
//                    e.printStackTrace();
//                }
//            }); // 唤醒 select 方法 boss
            sc.register(selector, SelectionKey.OP_READ, null); // boss
        }


        @Override
        public void run() {
            while (true) {
                try {
                    selector.select(); // worker-0 阻塞
//                    Runnable task = queue.poll();
//                    if (task != null) {
//                        task.run(); // 执行了sc.register(selector,SelectionKey.OP_READ,null);
//                    }
                    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                    while (iter.hasNext()) {
                        SelectionKey key = iter.next();
                        iter.remove();
                        if (key.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel channel = (SocketChannel) key.channel();
                            log.debug("read...{}",channel.getRemoteAddress());
                            channel.read(buffer);
                            buffer.flip();
                            System.out.println(StandardCharsets.UTF_8.decode(buffer).toString());
                        }
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
